package com.lw.leetcode.hash.a;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 599. 两个列表的最小索引总和
 *
 * @Author liw
 * @Date 2021/7/5 13:12
 * @Version 1.0
 */
public class FindRestaurant {
    public String[] findRestaurant(String[] list1, String[] list2) {
        int length = list1.length;
        HashMap<String, Integer> map = new HashMap<>(length << 1);
        for (int i = 0; i < length; i++) {
            map.put(list1[i], i);
        }
        List<String> res = new ArrayList<>();
        int min = Integer.MAX_VALUE;
        int sum;
        int l = list2.length;
        for (int j = 0; j < l && j <= min; j++) {
            String ley = list2[j];
            Integer value = map.get(ley);
            if (value != null) {
                sum = j + value;
                if (sum < min) {
                    res.clear();
                    res.add(ley);
                    min = sum;
                } else if (sum == min) {
                    res.add(ley);
                }
            }
        }
        return res.toArray(new String[0]);
    }
}
